﻿using DongFangGuoKai.WCSPlatform.WebApi.Controllers;
using DongFangGuoKai.WCSPlatform.WebApi.ExternalSystem.WMSConmmon;
using DongFangGuoKai.WCSPlatform.WebApi.Utils;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using S7.Net;
using System.Threading;

namespace DongFangGuoKai.WCSPlatform.WebApi.HostService
{
    /// <summary>
    /// 出库后台分拨任务
    /// </summary>
    public class OutWhouseHostService : BackgroundService
    {
        private readonly Plc plc;
        private readonly PlcTaskManager plcTaskManager;
        private readonly ILogger<OutWhouseHostService> logger;



        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="plc"></param>
        /// <param name="plcTaskManager"></param>
        /// <param name="logger"></param>
        public OutWhouseHostService
        (
            Plc plc,
            PlcTaskManager plcTaskManager,
            ILogger<OutWhouseHostService> logger
        )
        {
            this.plc = plc;
            this.plcTaskManager = plcTaskManager;
            this.logger = logger;
        }

  
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                Task.Run(async () =>
                {
                    logger.LogInformation("出库任务启动");
                    while (true)
                    {
                        try
                        {
                            if (plc.IsConnected)
                                plcTaskManager.OutDoWork();
                        }
                        catch (Exception ex)
                        {
                            logger.LogError("出库分拨窗口任务异常:" + ex.Message);
                        }
                        await Task.Delay(1000);
                    }

                });
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                logger.LogError($"出库分拨窗口任务异常：{ex.Message}");
                return Task.CompletedTask;
            }
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("出库后台任务异常结束");
            Dispose();
            return base.StopAsync(cancellationToken);
        }
    }
}
